package com.yisoo.ubag.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yisoo.common.constant.LoginStatusConstant;
import com.yisoo.common.utils.R;
import com.yisoo.ubag.app.manager.WxApiManager;
import com.yisoo.ubag.app.to.WxLoginResponseTo;
import com.yisoo.common.utils.MyBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yisoo.common.utils.PageUtils;
import com.yisoo.common.utils.Query;

import com.yisoo.ubag.app.dao.UserDao;
import com.yisoo.ubag.app.entity.UserEntity;
import com.yisoo.ubag.app.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
    @Autowired
    private WxApiManager wxApiManager;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(params),
                new QueryWrapper<UserEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R LoginAndReg(String code, String data) {
//        {"nickName":"mmciel","gender":1,"language":"zh_CN","city":"Xinyang","province":"Henan","country":"China","avatarUrl":"https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKh137Imo7ibuNKUz2qFF3lkaOWNcOJ6Gm4FKB2KnIReAamBFL0l9olnsn2yax44EzZ5s5zKQT6OaQ/132"}
//        UserEntity userEntity = JSONObject.parseObject(data, UserInfoTo.class).getUserEntity();
        UserEntity userEntity = JSONObject.parseObject(data, UserEntity.class);
        WxLoginResponseTo loginResponseTo = wxApiManager.runLogin(code);
        System.out.println(loginResponseTo);
        String openid = loginResponseTo.getOpenid();
        if (loginResponseTo.getErrcode() == null || loginResponseTo.getErrcode() == 0){
            //请求成功完成注册或者登录
            UserEntity user = getUserByOpenId(openid);
            if (user == null) {
                System.out.println("reg"+openid);
                //需要注册
                userEntity.setRegTime(new Date());
                userEntity.setAppUserId(openid);
                userEntity.setOpenid(loginResponseTo.getOpenid());
                userEntity.setSessionKey(loginResponseTo.getSession_key());
                userEntity.setLoginTime(new Date());
                userEntity.setPassword("123456");
                this.save(userEntity);
                stringRedisTemplate.opsForValue().set(LoginStatusConstant.APP_LOGIN_TOCKEN+userEntity.getOpenid(), userEntity.getOpenid(),60*10, TimeUnit.SECONDS);
                return R.ok().put("data",userEntity);
            }else{
                System.out.println("login"+openid);
                //登录并更新
//                UserEntity(appUserId=null, openid=oEBTC4g684wEqVtnDQoV-3RRJC94, sessionKey=TLoZwVmjzdplBTmDqC+TOg==, avatarUrl=https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTKh137Imo7ibuNKUz2qFF3lkaOWNcOJ6Gm4FKB2KnIReAamBFL0l9olnCt3nXDPYT7IucLR6KVoUFw/132, city=Xinyang, country=China, gender=1, language=zh_CN, nickName=mmciel, province=Henan, regTime=null, loginTime=null)
                MyBeanUtils.copyProperties(userEntity,user);
                user.setLoginTime(new Date());
                this.updateById(user);
                stringRedisTemplate.opsForValue().set(LoginStatusConstant.APP_LOGIN_TOCKEN+user.getOpenid(), user.getOpenid(),60*10, TimeUnit.SECONDS);
                return R.ok().put("data",user);
            }
            //TODO 缓存存一份
        }
        else {
            return R.error("服务器异常");
        }

    }

    @Override
    public UserEntity getUserByOpenId(String openid) {
        QueryWrapper<UserEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("openid",openid);
        List<UserEntity> userEntities = baseMapper.selectList(queryWrapper);
        if(userEntities != null && userEntities.size()>0){
            return userEntities.get(0);
        }
        return null;
    }

}